package com.bluexmicro.bluetooth.peripheral.handler

import android.annotation.SuppressLint
import android.bluetooth.BluetoothGatt
import com.bluexmicro.bluetooth.model.GattStatus
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume


typealias ReadRssiCallback = (
    gatt: BluetoothGatt,
    rssi: Int, status: Int
) -> Unit

class ReadRssiHandler {

    private var callback: ReadRssiCallback? = null
    private var cancellableContinuation: CancellableContinuation<Result<Int>>? = null

    fun onReadRemoteRssi(
        gatt: BluetoothGatt, rssi: Int, status: Int
    ) {
        callback?.invoke(gatt, rssi, status)
    }

    private fun setCallback(cb: ReadRssiCallback) {
        this.callback = cb
    }

    fun isActive(): Boolean {
        return cancellableContinuation?.isActive == true
    }

    @SuppressLint("MissingPermission")
    suspend fun execute(
        gatt: BluetoothGatt,
    ) = suspendCancellableCoroutine<Result<Int>> {
        cancellableContinuation = it
        setCallback { _, rssi, status ->
            if (it.isActive) {
                this.callback = null
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    it.resume(Result.success(rssi))
                } else {
                    val reason = GattStatus.fromValue(status).name
                    it.resume(Result.failure(IllegalArgumentException("Read Rssi Failed, gatt errorCode:$status, reason: $reason")))
                }
            }
        }
        if (it.isActive && !gatt.readRemoteRssi()) {
            this.callback = null
            it.resume(Result.failure(IllegalArgumentException("Read Rssi Failed")))
        }

        it.invokeOnCancellation {
            this.callback = null
        }
    }
}